Determine if integer is a power of two¶
Time: O(1); Space: O(1); easy
Given an integer, write a function to determine if it is a power of two.
[1]:
class Solution1(object):
def isPowerOfTwo(self, n) -> bool:
"""
:type n: int
:rtype: bool
"""
return n > 0 and (n & (n - 1)) == 0
[2]:
s = Solution1()
assert s.isPowerOfTwo(16) == True
assert s.isPowerOfTwo(24) == False
[3]:
class Solution2(object):
def isPowerOfTwo(self, n) -> bool:
"""
:type n: int
:rtype: bool
"""
# print(~-n) # 15, 23
return n > 0 and (n & ~-n) == 0
[4]:
s = Solution2()
assert s.isPowerOfTwo(16) == True
assert s.isPowerOfTwo(24) == False